import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { loginApi } from '@/api/commonApi'
import { clearLoginCache, getLocal, getSession, getTokenKey, setSession } from '@/util/utils'
import Login from '../views/home/Login.vue'
import IndexView from '../views/home/Index.vue'
import DefalutResource from '../views/devcloud/DefalutResource.vue'
import Env from '../views/devcloud/Env.vue'
import GitConfig from '../views/devcloud/GitConfig.vue'
import JenkinsConfig from '../views/devcloud/JenkinsConfig.vue'
import KubernetesConfig from '../views/devcloud/KubernetesConfig.vue'
import RegisterConfig from '../views/devcloud/RegisterConfig.vue'
import LogConfig from '../views/devcloud/LogConfig.vue'
import DomainConfig from '../views/devcloud/DomainConfig.vue'
import Product from '../views/devcloud/Product.vue'
import PublistIndex from '../views/publish/Index.vue'
import PublistProduct from '../views/publish/Product.vue'
import PublistProject from '../views/publish/Project.vue'
import { getEnvId, setEnvId } from '@/util/devcloudUtils'
import { envApi } from '@/api/devcloudApi'
import { message } from 'ant-design-vue'
import store from '@/store'


const routes: Array<RouteRecordRaw> = [
	{
		path: '/login',
		name: 'login',
		component: Login
	},
  {
    path: '/',
    component: IndexView,
    children: [
      {
        path: '/devcloud/defalutResource',
        component: DefalutResource
      },
      {
        path: '/devcloud/env',
        component: Env
      },
      {
        path: '/devcloud/gitConfig',
        component: GitConfig
      },
      {
        path: '/devcloud/jenkinsConfig',
        component: JenkinsConfig
      },
      {
        path: '/devcloud/kubernetesConfig',
        component: KubernetesConfig
      },
      {
        path: '/devcloud/registerConfig',
        component: RegisterConfig
      },
      {
        path: '/devcloud/product',
        component: Product
      },
      {
        path: '/devcloud/logConfig',
        component: LogConfig
      },
      {
        path: '/devcloud/domainConfig',
        component: DomainConfig
      },
    ]
  },
  {
    path: '/publish',
    name: 'publish',
    redirect: "/publish/product",
    component: PublistIndex,
    children: [
      {
        path: '/publish/product',
        component: PublistProduct
      },
      {
        path: '/publish/project',
        component: PublistProject
      },
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const initEnv = (path:string, next:any) => {
  if(!path.startsWith('/publish')){
    next()
    return
  }
  const envId = getEnvId()
  if(!envId){
    const param = {}
    envApi.list(param).then(res=>{
      if (res.success) {
        if(res.result.length == 0){
          message.warn("缺少环境配置")
          return
        }
        const envId = res.result[0].id
        setEnvId(res.result[0].id)
        initCurrInfo(envId)
        next()
        return
      }
      message.warn("环境配置获取失败")
    }).catch(e=>{
      console.log(e);
      
    })
  }
  initCurrInfo(envId)
  next()
}

const initCurrInfo = (envId:number) =>{
  const currEnvId = store.getters.getCurrInfo.envId
  if(currEnvId){
    return
  }
  store.commit('setCurrInfo', {'envId': envId})
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
	let token = getLocal(getTokenKey())
	// 有token则为登录状态
	if(token){
		// 获取个人权限信息
		let owner = getSession('devcloud-auth')
		// 没有个人信息则获取
		if(!owner || owner === 'undefined'){
			loginApi.systemAuth().then(resp=>{
				// 返回
				if(!resp.success){
					return
				}
				if(!resp.result){
					clearLoginCache()
					router.push({path:'/login'})
					return
				}
				setSession('devcloud-auth', JSON.stringify(resp.result))

        // 只有发布菜单，直接跳转
        if(resp.result.accountMenu && resp.result.accountMenu.length ===1 && resp.result.accountMenu[0].children && resp.result.accountMenu[0].children.length === 1 && resp.result.accountMenu[0].children[0].name === '产品发布'){
          router.push({path: '/publish'})
        }
				next()
				return
			})
			return
		}
		// 登录状态再次方位登录页面直接跳转
		if(to.fullPath === '/login'){
			router.push({path:'/'})
			return
		}
	}else {
		// 没有token直接跳转至登录页面
		if(to.fullPath !== '/login'){
			router.push({path:'/login'})
			return
		}
	}
	// 执行此次跳转
  initEnv(to.fullPath, next)
	
})
export default router
